<template>
  <div class="monaco-editor-cus">
    <div ref="el" class="go-editor-area" :style="{ width, height }"></div>
    <EditorWorker></EditorWorker>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, watch, PropType, ref} from 'vue'
import {useMonacoEditor} from './index.hook'
import {EditorWorker} from './index'
import * as monaco from 'monaco-editor'
// 定义支持的主题类型
type ThemeType = 'vs' | 'vs-dark' | 'hc-black' | 'custom-dark' | 'custom-light'

const props = defineProps({
  width: {
    type: String as PropType<string>,
    default: '100%'
  },
  height: {
    type: String as PropType<string>,
    default: '90vh'
  },
  language: {
    type: String as PropType<string>,
    default: 'typescript'
  },
  preComment: {
    type: String as PropType<string>,
    default: ''
  },
  modelValue: {
    type: String as PropType<string>,
    default: ''
  },
  editorOptions: {
    type: Object as PropType<object>,
    default: () => ({})
  },
  // 新增主题prop
  theme: {
    type: String as PropType<ThemeType>,
    default: 'vs'
  }
})

const emits = defineEmits(['blur', 'update:modelValue'])

const {el, updateVal, getEditor, createEditor} = useMonacoEditor(props.language)

const updateMonacoVal = (_val?: string) => {
  const {modelValue, preComment} = props
  const val = preComment ? `${preComment}\n${_val || modelValue}` : _val || modelValue
  updateVal(val)
}

// 定义自定义主题（如果需要）
const defineCustomThemes = () => {
  // 自定义深色主题
  monaco.editor.defineTheme('custom-dark', {
    base: 'vs-dark',
    inherit: true,
    rules: [
      {token: 'comment', foreground: '6A9955', fontStyle: 'italic'},
      {token: 'keyword', foreground: '569CD6'},
      {token: 'string', foreground: 'CE9178'},
      {token: 'function', foreground: 'DCDCAA'}
    ],
    colors: {
      'editor.background': '#1E1E1E',
      'editor.foreground': '#D4D4D4'
    }
  })
}
// 存储编辑器实例的引用
const editorInstance = ref(null)
onMounted(() => {
  // 先定义自定义主题（如果使用）
  defineCustomThemes()
  // 创建编辑器时合并主题配置
  const editorOptions = {
    ...props.editorOptions,
    theme: props.theme  // 关键：初始化时指定主题
  }

  const monacoEditor = createEditor(editorOptions)
  editorInstance.value = monacoEditor
  monacoEditor!.onDidChangeModelContent(() => {
    emits('update:modelValue', monacoEditor!.getValue())
  })
  monacoEditor!.onDidBlurEditorText(() => {
    emits('blur')
  })
  updateMonacoVal()
})
// 监听主题变化，动态切换
watch(
    () => props.theme,
    (newTheme) => {
      // 确保主题切换生效的关键代码
      if (newTheme) {
        // 先设置全局主题
        monaco.editor.setTheme(newTheme)
        // 如果有编辑器实例，重新应用主题
        if (editorInstance.value) {
          editorInstance.value.updateOptions({theme: newTheme})
        }
      }
    },
    {immediate: true}  // 立即执行一次，确保初始主题正确
)

watch(
    () => props.modelValue,
    (val: string) => {
      val !== getEditor()?.getValue() && updateMonacoVal(val)
    }
)
</script>

<style lang="scss" scoped>
.monaco-editor-cus {
  border: solid 1px #c8c8c8;

  .go-editor-area {
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    padding: 5px;
    padding-left: 0;
    box-sizing: border-box;
    // 移除可能覆盖主题背景的样式
    //background-color: transparent;
    //@include deep() {
    //  .margin,
    //  .monaco-editor,
    //  .inputarea.ime-input {
    //    background-color: rgba(0, 0, 0, 0);
    //  }
    //
    //  .monaco-editor-background {
    //    background-color: rgba(0, 0, 0, 0);
    //    @include fetch-bg-color('filter-color-shallow');
    //  }
    //  .margin {
    //    @include fetch-bg-color('filter-color-shallow');
    //  }
    //}
  }
}

</style>
